//
//  FBProfileController.m
//  piggy
//
//  Created by 宋质彬 on 2018/3/5.
//  Copyright © 2018年 宋质彬. All rights reserved.
//

#import "JSLProfileController.h"

#import "JSLHelpCenteryController.h"
#import "FBProfileCell.h"
#import "FBProfileHeaderView.h"
#import "SYJWXWarnView.h"
#import "AppConfig.h"
//#import "FBLoginController.h"
//#import "FBFeedBackController.h"
//#import "FBAboutController.h"
//#import "H5WebViewController.h"
#import "UserInfo.h"
#import "UserManager.h"

//#import "FBSettingController.h"
//#import "FBPersonInfoController.h"

#import "JSLSetController.h"

@interface JSLProfileController ()
<UITableViewDelegate,UITableViewDataSource,FBProfileHeaderViewDelegate,SYJWXWarnViewDelegate>
@property (nonatomic , strong) UITableView *tableView;
@property (nonatomic , strong) NSArray *arrayData;
@property (nonatomic , weak) FBProfileHeaderView *profileHeader;
@end

@implementation JSLProfileController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self tableView];
    
    [self configDataSource];
}


-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.navigationController.navigationBar.prefersLargeTitles = NO;
        
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    [self requestUserInfoData];
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}


#pragma mark - 获取用户信息
- (void)requestUserInfoData {
    // 设置token
    NSString *userToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
    parameters[@"userPhone"] = userToken;
    
    [HttpRequest POST:USERINFO_URL parameters:parameters success:^(id  _Nullable result, NSString * _Nullable successMessage) {
        
        NSLog(@"%@",result);
        NSDictionary *userDict = result[@"data"];
        
        // 创建用户模型
        UserInfo *userModel =   [UserInfo yy_modelWithJSON:userDict.yy_modelToJSONString];
        // 创建用户模型管理者
        [UserManager manager].userInfo = userModel;
        
        // 刷新登录状态
        [self.profileHeader refreshHerderWithUserinfo:userModel];
    } failure:^(NSInteger code, NSString * _Nullable errorMessage) {
        // 清空用户模型
        UserInfo *userModel = [UserInfo yy_modelWithJSON:@""];
        [UserManager manager].userInfo = userModel;
        [UserManager  logout];
        NSLog(@"%@",errorMessage);
        
    
        
        // 刷新登录状态
        [self.profileHeader refreshHerderWithUserinfo:userModel];
    }];
    
}
#pragma mark - get
- (UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height -64-49) style:UITableViewStylePlain];
        _tableView.scrollEnabled = NO;
        _tableView.sectionFooterHeight = 10 *AutoSizeScaleYY;
        _tableView.rowHeight = 64 *AutoSizeScaleYY;
        _tableView.backgroundColor = BACKGROUND_COLOR;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        [self.view addSubview:_tableView];
        
        
        // 设置表头
        
        FBProfileHeaderView *profileHeader = [[FBProfileHeaderView alloc] init];
        profileHeader.frame = CGRectMake(0, 0, self.view.width, 141 *AutoSizeScaleYY);
        profileHeader.delegate = self;
        
        _tableView.tableHeaderView = profileHeader;
        
        self.profileHeader = profileHeader;
        
        
    }
    
    return _tableView;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 配置数据
- (void)configDataSource {
    
    if ([AppConfig shareConfig].audit) {
        
        self.arrayData = @[
                           
                           @[
//                               @{@"heardImage":@"帮助-icon",
//                                 @"title":@"帮助中心",
//                                 @"rightTitle":@"",
//                                 @"flag":@"pesoninfo"
//                                 },
                               
                               @{@"heardImage":@"设置-icon",
                                 @"title":@"设置",
                                 @"rightTitle":@"",
                                 @"flag":@"setting"
                                 }
                               ],
                           
                           @[
                               @{@"heardImage":@"客服-icon",
                                 @"title":@"联系客服",
                                 @"rightTitle":@"",
                                 @"flag":@"yjfk"
                                 },
                               
//                               @{@"heardImage":@"公众号-icon",
//                                 @"title":@"关注公众号",
//                                 @"rightTitle":@"",
//                                 @"flag":@"wx"
//                                 }
                               ]
                           
                           ];
        
        
    }else{
        self.arrayData = @[
                           
                           @[
//                               @{@"heardImage":@"帮助-icon",
//                                 @"title":@"帮助中心",
//                                 @"rightTitle":@"",
//                                 @"flag":@"pesoninfo"
//                                 },
//
                               @{@"heardImage":@"设置-icon",
                                 @"title":@"设置",
                                 @"rightTitle":@"",
                                 @"flag":@"setting"
                                 }
                               ],
                           
                           @[
                               @{@"heardImage":@"客服-icon",
                                 @"title":@"联系客服",
                                 @"rightTitle":@"",
                                 @"flag":@"yjfk"
                                 },
                               
                               @{@"heardImage":@"公众号-icon",
                                 @"title":@"关注公众号",
                                 @"rightTitle":@"",
                                 @"flag":@"wx"
                                 }
                               ]
                           
                           ];
        
        
        
        
    }
    
}

#pragma mark - FBProfileHeaderViewDelegate
- (void)clickLoginButtonOnMeHeardView {
    
    if ([UserManager checkLogin:self]) {
        
    }

}

#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.arrayData.count;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [self.arrayData[section] count];
}


- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    FBProfileCell *cell = [FBProfileCell cellWithTableView:tableView];
    cell.infoDict = self.arrayData[indexPath.section][indexPath.row];
    return cell;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    return [JSLKitFactory jsl_viewWithFrame:CGRectMake(0, 0, self.view.width, 10*AutoSizeScaleYY) backgroundColor:nil superView:nil];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *infoDict = self.arrayData[indexPath.section][indexPath.row];
    if ([infoDict[@"flag"] isEqualToString:@"setting"]) {
        JSLSetController *modifyVC = [[JSLSetController alloc] init];
        [self pushViewController:modifyVC animated:YES];
    }else if ([infoDict[@"flag"] isEqualToString:@"wx"]) {
        [self contactWX];
        
    }else if ([infoDict[@"flag"] isEqualToString:@"yjfk"]) {
        [self contactQQ];
    }else if ([infoDict[@"flag"] isEqualToString:@"pesoninfo"]) {
        JSLHelpCenteryController *vc = [[JSLHelpCenteryController alloc] init];
        vc.fileName = @"help.html";
        vc.title = @"帮助中心";
        [self pushViewController:vc animated:YES];
    }
    NSLog(@"哈哈哈😁");
}

#pragma mark - SYJWXWarnViewDelegate
- (void)clickWXButtonAction:(SYJWXWarnView *)WXWarnView{
    
    NSDictionary *dict = [self configOpenUrl];
    //先判断是否能打开该url
    if ([dict[@"isOpenUrl"] integerValue] == 1)
        
    {
        [[SYJWXWarnView shareWXWarnView] WXWarnViewHideWithSuccess:^{
            //打开微信
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:dict[@"url"]]];
            
        } failure:^(NSError *error) {
            
        }];
        
    }else {
        
        [[SYJWXWarnView shareWXWarnView] WXWarnViewHideWithSuccess:^{
            [self alertShow];
        } failure:^(NSError *error) {
            
        }];
        
    }
}

- (NSDictionary *)configOpenUrl{
    
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"weixin://"]]) {
        
        return @{@"url":@"weixin://",@"isOpenUrl":@1};
        
    }else{
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"wechat://"]]) {
            return @{@"url":@"wechat://",@"isOpenUrl":@1};
        }else{
            return @{@"url":@"wechat://",@"isOpenUrl":@0};
        }
    }
}
- (void)alertShow
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"跳转异常" message:@"请确认是否安装过微信" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark 点击客服QQ
- (void)contactQQ
{
    /**
     NSURL * url = [NSURL URLWithString:@"weixin://"];
     BOOL canOpen = [[UIApplication sharedApplication] canOpenURL:url];
     //先判断是否能打开该url
     if (canOpen)
     {   //打开微信
     [[UIApplication sharedApplication] openURL:url];
     }else {
     */
    
    BOOL success = [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"mqqwpa://im/chat?chat_type=wpa&uin=2122706723&version=1&src_type=web&web_src=file:://"]]];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self alertShow:success ? @"1" : @"0"];
    });
}
- (void)alertShow:(NSString *)success
{
    if ([success isEqualToString:@"0"]) {
        UIAlertView *alertView =  [[UIAlertView alloc] initWithTitle:@"" message:@"跳转异常，请确认是否安装过qq" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
        
        [alertView show];
    }
}

- (void)contactWX
{
    SYJWXWarnView *wxwarnView = [SYJWXWarnView shareWXWarnView];
    wxwarnView.WXWarnViewDelegate = self;
    [wxwarnView WXWarnViewShowWithSuccess:^{
        
        UIPasteboard *pboard = [UIPasteboard generalPasteboard];
        //这其实就是一个剪切板  UIPasteboard
        pboard.string = @"叮当花花";
        
    } failure:nil];
}
- (UIStatusBarStyle)preferredStatusBarStyle{
    
    return UIStatusBarStyleLightContent;
    
}
@end
